// const utils = require("../../../common/util/util")
const app = getApp()
const text = require('../../../common/util/text.js')
Page({
    data: {
        xPageReady : true ,
        xRegister : true ,
        xUserInfo : '' ,
        xDoctor : '' ,
        xProductnew:'',
        week:0,
        treatmentList:[],
        weekList:[], //new
        xTes:true,
        show_week_change:false,
        treatment_history:[
          {icon:'icon-gengduo font-20',title:'第一周: 认识纤维肌痛综合征'},
          {icon:'icon-24gf-chartBarUpward font-22',title:'第二周: 循序渐进提升身体机能'},
          {icon:'icon-brain font-22',title:'第三周: 运用CBT解决情绪困扰'},
          {icon:'icon-icon-test font-22',title:'第四周: 自我关爱与放松'},
          {icon:'icon-yiwancheng font-20',title:'第五周: 慢性疼痛的治疗方案管理'},
          {icon:'icon-iconjsyl font-28',title:'第六周: 如何进行压力管理'},
          {icon:'icon-associate-full font-22',title:'第七周: 沟通技巧化解人际关系困扰 '},
          {icon:'icon-danao font-28',title:'第八周: 保持正念'}
        ], //历史课程信息
        QAList:[],
        camping_period_begin_date:'',
        params:false,
        is_read:false,
        taskList:[],
        nickNameM:false,
        needSetting:app.globalData.needAuthorization // 是否需要授权隐私协议
    },
    onShareAppMessage: function () {
      return {
        title: '疼痛久治不愈？还有一招',
        path: '/pages/navigation/index/index',
        imageUrl: 'https://7633-v3-92ah4-1300208657.tcb.qcloud.la/static/share_all.jpg',
      }
    },
    onHide:function(){
      this.setData({
        nickNameM:false
      })
    },
    onLoad: function (options) {
      let that = this
      that.setData({
        params:options
      })
      that.xInfo()
      that.getWeek()
    },
    // 下拉刷新
    onPullDownRefresh: function() {
      let that =this
      wx.setStorageSync('task', [])
      that.xInit()
      wx.stopPullDownRefresh()
    },
    // 用户数据检查
    xInfo:function () {
      let that = this
      if(that.data.isreturn) {
        that.getHistory(that.data.week)  
        return
      } 
      wx.cloud.callFunction({
          name : 'user' ,
          data : {
              action : 'detail'
          }
      }).then( res => {
        let user = res.result
        if(!user._id){
          let additional={
            is_overdue_free_program:false,
            is_open_business:false,
            buy_status:0,
            is_add_free_program:false,
          }
          that.setData({
            xUserInfo : {},
            xPageReady:false,
            additional:additional
          })
        }else{
          app.globalData.xCustomer = user
          app.globalData.user = user
          that.setData({
            xUserInfo : user , //用户信息
            xConsultationTeacher : user.consultation_teacher_info ? user.consultation_teacher_info[0]:'', //咨询师
          })
          // 获取用户任务
          that.xInit()
        }
      })
    },
    // 初始化
    xInit: async function () {
        let that = this
        app.xTodayLast()
        if(that.data.isreturn) {
          that.getHistory(that.data.week)  
          return
        } 
        wx.cloud.callFunction({
          name: 'digital_therapy',
          data: {
            action: "get_going_project"
          }
        }).then(res => {
            // res.result.additional.is_mixed_standardscoles = true
            // res.result.additional.treatment_completion_status=false
            // res.result.additional.is_overdue_free_program=true
            // res.result.additional.is_open_business=false
            // res.result.additional.buy_status=0
            // res.result.additional.is_add_free_program=true
            let data = res.result
            that.setData({
              week: res.result.additional.week,
              additional:res.result.additional,
              xProductnew:res.result,
              is_read:res.result.is_task_open
            })
            // 数据排序
            that.xTaskSort(res.result)
            // 更新全局产品购买状态
            if(res.result.additional.buy_status !=0 ){
              app.globalData.product_buy =true
            }
            // 所有任务已完成获取默认工具包
            if(res.result.additional.treatment_completion_status && res.result.additional.buy_status !==0){
              that.xGetTool()
            }
            // 已购买且未开营获取开营日期
            if(res.result.additional.buy_status!=0 && !res.result.additional.is_open_business){
              that.getPeriod()
            }
            // 获取每周问答
            that.xGetQA(res.result.additional.week)
            // 获取日历
            // that.xGetCalendar()
            that.setData({
              xPageReady : false
            })
            data.additional.week > 4 && !data.scale_exists ?  that.xCheckCompleteEvaluation(data.scale_visit) :''
            // that.xCheckCompleteEvaluation(data.scale_visit)
        })
    },
    xCheckCompleteEvaluation(scale_visit){
      // const app = getApp()
      // if(app.globalData.needCompleteEvaluation){
        console.log("执行")
        wx.showModal({
          title: '提示',
          content: '请先完成评估量表',
          showCancel:false,
          complete: (res) => {
            if (res.confirm) {
              let encodedUrl = encodeURIComponent(scale_visit);
              wx.reLaunch({
                url: '/subsale/pages/webViewEvaluation/index?url=' +  encodedUrl 
              })
            }
          }
        })
      // }
    },
    // 获取日历内容
    xGetCalendar(){
      let that = this
      wx.cloud.callFunction({
        name: 'digital_therapy_extend',
        data: {
           action:"get_task_completion_calendar"
        }
      }).then(res => {
        that.setData({
          calendarInfo:res.result
        })
      }) 
    },
    // 获取答疑内容
    xGetQA(week){
      let that = this
      wx.cloud.callFunction({
        name: 'digital_therapy_extend',
        data: {
          action: "get_practic_answering_questions",
          week: week,//当前练习的存在的阶段（周）
          is_index:true
        }
      }).then(res => {
        for(let index in res.result){
          res.result[index].show =false
          res.result[index].answer = text.text(res.result[index].answer)
        }
        that.setData({
          QAList:res.result
        })
      })
    },
    // 获取开营日期
    getPeriod:function(){
      let that = this
      wx.cloud.callFunction({
        name: 'product',
        data: {
          action: "get_period_list"
        }
      }).then(res => {
        // res.result.camping_period_begin_date = utils.formatDate_chinese(new Date(res.result.camping_period_begin_date))
        that.setData({
          PeriodList:res.result
        })
      })
    },
    // 咨询师QR
    xToQR:function(){
      let that =this;
      var url= 'https://7633-v3-92ah4-1300208657.tcb.qcloud.la/static/buy_customer.png?time='+Date.now() //地址加上时间戳，否则从缓存中加载
      wx.previewImage({
        urls: [url],
      })
    },
    // 获取工具包
    xGetTool(){
      let that =this
      wx.cloud.callFunction({
        name: 'digital_therapy_extend',
        data: {
            action: "get_all_treatment_item"
        }
      }).then(res => {
          that.setData({
            treatmentList:res.result
          })
      })
    },
    // 获取当前日期
    getWeek:function(){
      let that = this
      // Date.now() + 86400000 * 9
      var day3 = new Date();
      day3.setTime(day3.getTime() );
      var s3 = day3.getFullYear() + "-" + (day3.getMonth() + 1) + "-" + day3.getDate();
      let days = [];
      for (let i = 0; i <= 24 * 6; i += 24) {
        //今天加上今天的后6天
        // let dateItem=new Date(Date.getTime() - i * 60 * 60 * 1000);	//使用（当天）时间戳减去以前的时间毫秒（小时*分*秒*毫秒）
        let dateItem = new Date(day3.getTime() + i * 60 * 60 * 1000); //使用（第二天）时间戳减去以前的时间毫秒（小时*分*秒*毫秒）
        let y = dateItem.getFullYear(); //获取年份
        let m = dateItem.getMonth() + 1; //获取月份js月份从0开始，需要+1
        let d = dateItem.getDate(); //获取日期
        m = this.addDate0(m); //给为单数的月份补零
        d = this.addDate0(d); //给为单数的日期补零
        let valueYear = y + "-" + m + "-" + d; //组合
        let valueItem = d; //我只要一个日期
        var myddy = dateItem.getDay(); //获取存储当前日期
        var weekday = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
        days.push({
          date: `${valueItem}`,
          week: `${weekday[myddy]}`,
          name: `${i}`,
          dateYear: `${valueYear}`
        }); //添加至数组
      }
      that.setData({
        weekList:days
      })
    },
    // 单位日期补0
    addDate0:function(time) {
      if (time.toString().length == 1) {
        time = "0" + time.toString();
      }
      return time;
    },
    // 添加训练方案
    addPlan:function(e){
      let that = this
      // if(!that.data.xUserInfo.phone_number){
      //   let path = that.data.additional.is_mixed_standardscoles?'/subsale/pages/choosePlan/index/index':'/subuser/pages/research/index'
      //   let parmas = '&type=choosePlan'
      //   wx.navigateTo({
      //     url: '/pages/navigation/login/index?path='+path+parmas,
      //   })
      // }else{
        if(that.data.additional.is_mixed_standardscoles){
          wx.navigateTo({
            url: '/subsale/pages/choosePlan/index/index',
          })
        }else{
          wx.navigateTo({
            url: '/subuser/pages/research/index?type=choosePlan',
          })
        }
      // }
    },
    // 添加医生
    addDoctor:function(){
      wx.navigateTo({
        url: '/subuser/pages/doctoradd/index',
      })
    },
    // 查看p值数据
    xToSeePValue:function(){

    },
    // 前往疼痛指标
    xToPain:function(){

    },
		// 任务已完成提示
    xTofin(){
      wx.showModal({
        title: "提示",
        content: "此项任务今天已完成，请明天继续",
        showCancel: false,
        confirmText:'好的'
      })
    },
    // 任务展开收起
    xToAllTask:function(){
      this.setData({
        showTask : !this.data.showTask
      })
    },
    // 日历展开收起
    xToAllCalendar:function(){
      this.setData({
        showCancel : !this.data.showCancel
      })
    },
    // 未完成患教内容提示
    xToFinishCourse:function(){
      wx.showModal({
        title: '提示',
        content: '请先完成必读课内容',
        showCancel:false,
        confirmText:'我知道了'
      })
    },
    // 前往小测验
    xToTechEvl: function (e) {
      let that = this
      let params = e.currentTarget.dataset
      if(that.data.xTes){
        wx.navigateTo({
          url: '/subsale/pages/techevl/index/index?week=' + params.week +'&treatment_item_id='+params.treatment_item_id
        })
      }else{
        wx.navigateTo({
          url: '/subsale/pages/techevlR/index/index?week=' +  params.week+'&treatment_item_id='+params.treatment_item_id
        })
      }
    },
    // 目标
    xToTarget:function(e){
      let that =this
      let params = e.currentTarget.dataset
      // if(!that.data.xUserInfo.phone_number){
      //   let path = '/subsale/pages/product/targetMilepost/index'
      //   wx.navigateTo({
      //     url: '/pages/navigation/login/index?path='+path,
      //   })
      // }else{
        wx.navigateTo({
          url: '/subsale/pages/product/targetMilepost/index?week='+ params.week +'&treatment_item_id='+ params.treatment_item_id,
        })
      // }
      
    },
    // 治疗清单
    xTotreatmentlist:function(e){
        let that =this
        let d =e.currentTarget.dataset
        // if(!that.data.xUserInfo.phone_number){
        //   let path = '/subtool/pages/treatmentlist/index/index'
        //   let parmas = '&treatment_item_id='+ _id+'&type=1'
        //   wx.navigateTo({
        //     url: '/pages/navigation/login/index?path='+ path + parmas,
        //   })
        // }else{
          wx.navigateTo({
            url: '/subtool/pages/treatmentlist/index/index?treatment_item_id='+ d.treatment_item_id+'&type=1'+'&week='+d.week
          })
        // }
    },
    // 视频练习 腹式呼吸
    xTovideo : function ( e ) {
      let that =this;
      if(that.data.is_read){
        // if(!that.data.xUserInfo.phone_number){
        //   let path = '/pages/navigation/using/index'
        //   wx.navigateTo({
        //     url: '/pages/navigation/login/index?path='+path,
        //   })
        // }else{
            let params = e.currentTarget.dataset
            // if(params.today==params.frequency_daily){
            //   that.xTofin()
            //   return
            // }
            wx.navigateTo({
              url: '/subtool/pages/video/index/index?treatment_item_id=' + params.treatment_item_id +'&week='+ params.week +'&audio_id='+params.audio_id
            })
        // }
      }else{
        that.xToFinishCourse()
      }
    },
    // 音频练习
    xToPlay: function ( e ) {
      let that =this;
      if(that.data.is_read){
        // if(!that.data.xUserInfo.phone_number){
        //   let path = '/pages/navigation/using/index'
        //   wx.navigateTo({
        //     url: '/pages/navigation/login/index?path='+path,
        //   })
        // }else{
          let params = e.currentTarget.dataset
          // if(params.today == params.frequency_daily){
          //   that.xTofin()
          //   return
          // }
          wx.navigateTo({
              url: '/subtool/pages/rudio/detail/index?treatment_item_id='+params.treatment_item_id+'&week=' + params.week +'&audio_id=' + params.audio_id
          })
        // }
      }else{
        that.xToFinishCourse()
      }
    },
    // 循环练习
    xToAction:function(e){
      let that =this
      let week =e.currentTarget.dataset.week
      let id = e.currentTarget.dataset.treatment_item_id
      let status = e.currentTarget.dataset.physiotherapy_today_completed_status
      // if(!that.data.xUserInfo.phone_number){
      //   let path = '/subtool/pages/action/index/index'
      //   let params = '&week='+week+'&treatment_item_id='+id+'&type=1'
      //   wx.navigateTo({
      //     url: '/pages/navigation/login/index?path='+path + params,
      //   })
      // }else{
        wx.navigateTo({
            url: '/subtool/pages/action/index/index?week='+week+'&treatment_item_id='+id+'&type=1',
        })
      // }
    },
    // 放松练习
    xToRelaxaudio:function(e){
      let that =this
      let week =e.currentTarget.dataset.week
      let id = e.currentTarget.dataset.treatment_item_id
      let count =e.currentTarget.dataset.count
      let status= e.currentTarget.dataset.status
      let num =e.currentTarget.dataset.num
      // if(!that.data.xUserInfo.phone_number){
      //   let path = '/subtool/pages/relaxaudioall/index/index'
      //   let params = '&week='+week+'&treatment_item_id='+id+'&type=1'+'&count='+count+'&status='+status+'&num='+num
      //   wx.navigateTo({
      //     url: '/pages/navigation/login/index?path='+path + params,
      //   })
      // }else{
        wx.navigateTo({
            url: '/subtool/pages/relaxaudioall/index/index?week='+week+'&treatment_item_id='+id+'&type=1'+'&count='+count+'&status='+status+'&num='+num,
        })
      // }
    },
    // 书写练习
    todayremb: function(e){
      let that =this
      let d = e.currentTarget.dataset
      // if(!that.data.xUserInfo.phone_number){
      //   let path = '/subtool/pages/dayremb/detail/index'
      //   let params = '&id=' + d.id + '&num=' + d.num + '&week='+ d.week +'&title=' + d.name+'&day='+this.data.xProductnew.additional.day+'&treatment_item_id='+ d.id+'&type=1'
      //   wx.navigateTo({
      //     url: '/pages/navigation/login/index?path='+path +params,
      //   })
      // }else{
        if(d.today>=d.frequency_daily){
          that.xTofin()
          return
        }
        wx.navigateTo({
          url: '/subtool/pages/dayremb/detail/index?id=' + d.id + '&num=' + d.num + '&week='+ d.week +'&title=' + d.name+'&day='+this.data.xProductnew.additional.day+'&treatment_item_id='+ d.id+'&type=1',
        })
      // }
    },
    // 前往全部阶段
    xToProce: function (e) {
        let that = this
        let id = that.data.xProductnew.additional.product_id
        let status = that.data.xProductnew.additional.treatment_completion_status
        let week = e.currentTarget.dataset.week
        // if(!that.data.xUserInfo.phone_number){
        //   let path = '/subsale/pages/product/proce/index'
        //   let params = '&id=' + id+'&week='+ week +'&status='+that.data.xProductnew.additional.treatment_completion_status
        //   wx.navigateTo({
        //     url: '/pages/navigation/login/index?path='+path +params,
        //   })
        // }else{
          wx.navigateTo({
              url: '/subsale/pages/product/proce/index?id=' + id+'&week='+ week +'&status='+that.data.xProductnew.additional.treatment_completion_status
          })
        // }
    },
    // 阅读
    xToTech: function (e) {
        let that =this
        let data = e.currentTarget.dataset
        let ischange = this.data.xProductnew.additional.week == this.data.week ? 1 :2
        // if(!that.data.xUserInfo.phone_number){
        //   let path = '/subsale/pages/product/tech/index'
        //   let parmas = '&education_content_id='+data.education_content_id+'&type=1&week='+data.week+'&day='+data.day+'&change='+ischange
        //   wx.navigateTo({
        //     url: '/pages/navigation/login/index?path='+ path + parmas,
        //   })
        // }else{
          wx.navigateTo({
              url: '/subsale/pages/product/tech/index?education_content_id='+data.education_content_id+'&type=1&week='+data.week+'&day='+data.day+'&change='+ischange
          })
        // }
    },
    //前往疼痛日记
    xToPaindiary: function ( e ){
      let that =this
      let d = e.currentTarget.dataset
      // if(!that.data.xUserInfo.phone_number){
      //   let path = '/subsale/pages/product/paindiary/index'
      //   let params = '&week='+ d.week+'&day='+d.day+'&treatment_item_id='+ d.treatment_item_id+'&index='+d.index+'&type=1'
      //   wx.navigateTo({
      //     url: '/pages/navigation/login/index?path='+path +params,
      //   })
      // }else{
        if( d.today >= d.frequency_daily){
          that.xTofin()
          return
        }
        wx.navigateTo({
          url: '/subsale/pages/product/paindiary/index?week='+d.week+'&day='+d.day+'&treatment_item_id='+ d.treatment_item_id+'&index='+d.index+'&type=1',
        })
      // }
    },
    // 压力源
    xToPressuresource:function(e){
        let that =this;
        let id= e.currentTarget.dataset.treatment_item_id
        let week =e.currentTarget.dataset.week
        let status =e.currentTarget.dataset.status
        // if(!that.data.xUserInfo.phone_number){
        //   let path = '/subtool/pages/pressuresource/index/index'
        //   let params = '&treatment_item_id='+ id +'&type=1'+'&week='+week+'&today_pressure_source_status='+ status
        //   wx.navigateTo({
        //     url: '/pages/navigation/login/index?path='+path + params,
        //   })
        // }else{
          wx.navigateTo({
            url: '/subtool/pages/pressuresource/index/index?treatment_item_id='+ id +'&type=1'+'&week='+week+'&today_pressure_source_status='+ status
          })
        // }
    },
    // 沟通技巧
    xTocommunication:function(e){
      let that =this;
      let id= e.currentTarget.dataset.treatment_item_id
      let week =e.currentTarget.dataset.week
      let status =e.currentTarget.dataset.status
      // if(!that.data.xUserInfo.phone_number){
      //   let path = '/subtool/pages/communication/index/index'
      //   let params = '&treatment_item_id='+ id +'&type=1'+'&week='+week+'&today_communication_skills_status='+status
      //   wx.navigateTo({
      //     url: '/pages/navigation/login/index?path='+path +params,
      //   })
      // }else{
        wx.navigateTo({
          url: '/subtool/pages/communication/index/index?treatment_item_id='+ id +'&type=1'+'&week='+week+'&today_communication_skills_status='+status
        })
      // }
    },
    // 用户综合测评
    xToUserall:function(e){
      let params =e.currentTarget.dataset
      if(params.status){
        wx.showModal({
          title: "提示",
          content: "您已完成该项测评",
          showCancel: false,
          confirmText:'好的'
        })
      }else{
        wx.navigateTo({
          url: '/subuser/pages/research/index?type=4&week='+ params.week+'&treatment_item_id='+ params.treatment_item_id,
        })
      }
    },
    // 疼痛评估问卷
    xToUserDetail: function () {
        let that =this
        // if(!that.data.xUserInfo.phone_number){
        //   let path = '/subuser/pages/research/index'
        //   wx.navigateTo({
        //     url: '/pages/navigation/login/index?path='+path,
        //   })
        // }else{
          if(that.data.additional.is_mixed_standardscoles){
            wx.showModal({
              title: "提示",
              content: "您已完成该项测评",
              showCancel: false,
              confirmText:'好的'
            })
          }else{
            wx.navigateTo({
              url: '/subuser/pages/research/index',
            })
          }
        // }
       
    },
    // 个人病史补充
    xToUserDetail_b:function(){
      let that =this
      // if(!that.data.xUserInfo.phone_number){
      //   let path = '/subuser/pages/information/index'
      //   wx.navigateTo({
      //     url: '/pages/navigation/login/index?path='+path,
      //   })
      // }else{
        if(!this.data.xUserInfo.real_name && !this.data.xUserInfo.hard_calm_down){
          wx.navigateTo({
            url: '/subuser/pages/information/index',
          })
        }else{
          wx.showModal({
            title: "提示",
            content: "您已完成该项测评",
            showCancel: false,
            confirmText:'好的'
          })
        }
      // }
    },
    // 隐私协议弹窗
    handleTouchInput:function(){
      this.setData({
        innerShow:true
      })
    },
    changePrivacySetting:function(e){
      this.setData({
        needSetting:false
      })
    },
    xNickName:function(){
      wx.hideToast()
      this.setData({
        nickNameM: !this.data.nickNameM,
        needSetting:app.globalData.needAuthorization
      })
    },
    bindnicknamereview:function(){
      wx.hideToast()
    },
    // 设置昵称
    xInput:function(e){
      this.setData({
        nickName:e.detail.value
      })
    },
    bindblur:function(e){
      this.setData({
        nickName:e.detail.value
      })
    },
    xSetNickName:function(){
      let that = this
      if(that.data.nickName){
        wx.cloud.callFunction({
          name: "user",
          data: {
              action: "edit",
              formdata: {
                nickName:that.data.nickName
              }
          }
        }).then(res => {
            that.setData({
              nickNameM:false
            })
            wx.showToast({
              title: '个人资料已完善',
              icon:'none',
              duration:1500
            })
            setTimeout(function(){
              that.xToQR()
            },1000)
        })
      }
    },
    // 打卡规则
    xToClockRules:function(){
      wx.navigateTo({
        url: '/subsale/pages/clockRules/index/index',
      })
    },
    // 前往产品详情
    xToProduct(){
      wx.navigateTo({
        url: '/subsale/pages/product/index/index?id=26da8e4962b93a6000ec7c3d68d9d3eb',
      })
    },
    // 前往咨询师聊天
    xToMessage:function(e){
      let that = this;
      let params = e.currentTarget.dataset
      let id = params.id
      let ava = params.ava
      let name = params.name
      if(that.data.xProductnew.additional.buy_status==0){
        wx.showToast({
          title: '只有加入治疗计划后，才能与咨询师进行沟通哦',
          icon:'none'
        })
      }else{
        wx.navigateTo({
          url: '/subsale/pages/product/chat/index?id=' + id + '&name=' + name + '&ava=' + ava,
        })
      }
    },
    // 是否完成阅读
    xWarning: function () {
        wx.showToast({
            title: '请先完成课件阅读',
            icon: 'none'
        })
    },
    // 前往工具包
    xToTool(){
      let that =this
      // if(!that.data.xUserInfo.phone_number){
      //   let path = '/subtool/pages/treatmentTool/index/index'
      //   wx.navigateTo({
      //     url: '/pages/navigation/login/index?path='+path,
      //   })
      // }else{
        wx.navigateTo({
          url: '/subtool/pages/treatmentTool/index/index',
        })
      // }
    },
    // 查看历史课程
    xToChange(){
      let that =this;
      that.setData({
        show_week_change:!that.data.show_week_change
      })
      // wx.hideTabBar()
    },
    // 切换课程
    task_change(e){
        let that =this
        let week = e.currentTarget.dataset.week
        wx.setStorageSync('task', [])
        that.xGetQA(week)
        if(week == that.data.xProductnew.additional.week){
          that.setData({
            show_week_change:false,
            isreturn:false
          })
          that.xInit()
          return
        }else{
          that.setData({
            isreturn:true
          })
        }
        that.getHistory(week)
        wx.pageScrollTo({
          duration: 0,
          scrollTop: 0
        })
    },
    getHistory:function(week){
      let that = this
      wx.cloud.callFunction({
        name: 'digital_therapy',
        data: {
          action: "get_history_content",
          dataObj:{
            week:week,
            is_all:false
          }
        }
      }).then(res => {
        that.setData({
          // ['xProductnew.cognitive_education_content']:res.result[0].education_content,
          // ['xProductnew.treatment_item_content']:res.result[0].treatment_item,
          week : week,
          show_week_change:false,
          showTask:false,
          is_read:res.result[0].is_task_open
        })
        wx.setStorageSync('task', [])
        let obj = {
          treatment_item_content:res.result[0].treatment_item,
          cognitive_education_content:res.result[0].education_content
        }
        that.xTaskSort(obj)
        
      })
    },
    xReturn:function(){

    },
    // 本周答疑
    xToQAWeek:function(){
      let that=this
      wx.navigateTo({
        url: '/subsale/pages/QAWeek/index?week='+that.data.week,
      })
    },
    // 消息订阅
    xSubscribeMessage:function(){
      let that = this
      wx.requestSubscribeMessage({
        tmplIds: [
            "zdhHVTsEJBOL1Fvf_pRLeHT03em4xaduuN7As0nGU0g"
        ],
        success: (res) => {
            if (res['zdhHVTsEJBOL1Fvf_pRLeHT03em4xaduuN7As0nGU0g'] === 'accept') {
                // let dates = that.data.PeriodList.camping_period_begin_date.replace('年','-')
                // let datenew = dates.replace('月','-')
                // let dateN = datenew.replace('日','')
                wx.cloud.callFunction({
                    name: 'subscription_message_management',
                    data: {
                        action: "save_subscription_message",
                        tmplIds:['zdhHVTsEJBOL1Fvf_pRLeHT03em4xaduuN7As0nGU0g'], //模板ids
                        sead_date:that.data.PeriodList.camping_period_begin_date,//这里传当前用户的开营时间source:1
                    }
                }).then(res => {
                    that.setData({
                      [`additional.is_subscribe_alerts`]:true
                    })
                    wx.showToast({
                        title: '订阅成功',
                        icon: 'none',
                        duration: 1000,
                    })
                })
            }
        },
        fail() { }
      })
    },
    xTaskSort:function(data){
        let that = this
        let task_complete = []
        let task_no = []
        let value = JSON.parse(JSON.stringify(wx.getStorageSync('task')));
        let taskList = []
        for(let index in data.cognitive_education_content){
          taskList.push(data.cognitive_education_content[index])
        }
        for(let index in data.treatment_item_content){
          taskList.push(data.treatment_item_content[index])
        }
        let newarr = value.length > 0 ? JSON.parse(JSON.stringify(value)) :  JSON.parse(JSON.stringify(taskList))
        // 排序开始
        for(let index in  taskList){
            if(taskList[index].num==7){
              // 目标
              if(taskList[index].user_target_quantity >= taskList[index].completion_times){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }else if(taskList[index].num==3){
              // 单个音频
              if(taskList[index].mindfulness_practice_today_completed_count >= taskList[index].frequency_daily){
                task_complete.push(taskList[index])
              }else{
                task_no.push(newarr[index])
              }
            }else if(taskList[index].num==4 || taskList[index].num==5){
              // 动作练习
              if(taskList[index].physiotherapy_today_completed_status){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }else if(taskList[index].num==8 || taskList[index].num==12 ){
              // 放松练习
              if(taskList[index].today_practice_punching_completed_status){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }else if(taskList[index].num==2){
              // 书写练习
              if(taskList[index].diary_practice_today_completed_count>= taskList[index].frequency_daily){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }else if(taskList[index].num==9){
              // 治疗清单
              if(taskList[index].today_user_perception_treatment_status){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }else if(taskList[index].num==10){
              // 压力源分析
              if(taskList[index].today_pressure_source_status){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }else if(taskList[index].num==11){
              // 沟通技巧
              if(taskList[index].today_communication_skills_status){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }else if(taskList[index].num==6){
              // 疼痛日记
              if(taskList[index].pain_diary_today_completed_quantity >= taskList[index].frequency_daily){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }else if(taskList[index].num==13){
              // 用户综合测评
              if(taskList[index].user_test_status){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }else if(taskList[index].num==16){
              // 小测验
              if(taskList[index].today_quiz_result_count>= taskList[index].frequency_daily){
                task_complete.push(taskList[index])
              }else{
                task_no.push(taskList[index])
              }
            }
        }
        if(value.length == 0){
          let sortTask = []
          for(let index in task_no){
            sortTask.push(task_no[index])
          }
          for(let index in task_complete){
            sortTask.push(task_complete[index])
          }
          for(let index in taskList){
            if(taskList[index].content){
              if(taskList[index].is_read){
                sortTask.push(taskList[index])
              }else{
                if(taskList[index].is_must_learn){
                  sortTask.unshift(taskList[index])
                }else{
                  sortTask.push(taskList[index])
                }
              }
            }
          }
          newarr = JSON.parse(JSON.stringify(sortTask))
        }
        let newTask = JSON.parse(JSON.stringify(newarr))
        newarr.forEach((item,index1)=>{
          taskList.forEach((item2,index2)=>{
            if(newarr[index1]._id == taskList[index2]._id && newarr[index1].title !=undefined && taskList[index2].title != undefined ) {
              newTask[index1] = item2
            }
            if(newarr[index1]._id == taskList[index2]._id && newarr[index1].num !=undefined && taskList[index2].num != undefined ) {
              newTask[index1] = item2
            }
          })
        })
        for(let index in newTask){
          if(index ==0 ){
            if(!newTask[index].is_read && newTask[index].is_must_learn){
              newTask[index].text ='完成上述课程后，解锁其他任务'
            }
            if(newTask[index].is_read && newTask[index].is_must_learn){
              newTask[index].text ='已完成，任务已解锁'
            }
          }else {
            if(!newTask[index].is_read && newTask[index].is_must_learn){
              newTask[index].text ='完成上述课程后，解锁其他任务'
              newTask[index-1].text =''
            }
            if(newTask[index].is_read && newTask[index-1].is_read){
              newTask[index].text ='已完成，任务已解锁'
              newTask[index-1].text =''
            }
            if(index == newTask.length -1 ){
              newTask[index].text =''
            }
            if( Number(index) < newTask.length-1){
              if( !newTask[Number(index) + (Number(1))].is_must_learn && newTask[Number(index) + (Number(1))].title){
                newTask[index].text =''
              }
            }
          }
        }
        wx.setStorageSync('task', newTask)
        let arr =[]
        // 展示的5个任务
        let num = 0
        let read_num = 0
        for(let index in  data.cognitive_education_content){
          if(data.cognitive_education_content[index].is_must_learn && !data.cognitive_education_content[index].is_read && !data.cognitive_education_content[index].is_today_read){
            num++
          }
          if(data.cognitive_education_content[index].is_must_learn && data.cognitive_education_content[index].is_read && data.cognitive_education_content[index].is_today_read){
            read_num ++ 
            num ++
          }
        } 
        for(var i =0;i< 5;i++){
          if(newTask.length>i){
            arr.push(newTask[i])
          }
        }
        that.setData({
          'xProductnew.task':newTask,
          taskList:arr,
          completeTask:task_complete.length + read_num , //今日完成的任务数量
          todayTask: data.treatment_item_content.length +  num  //今日需要完成的任务数量
        })
    }
})